package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.Question;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.TodayBest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanHuaService {
    @Autowired
    private RecommendUserService recommendUserService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private QuestionService questionService;
    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;
    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;
    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;
    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    @Value("${tanhua.default.recommend.users}")
    String defaultRecommendUsers;
    @Autowired
    private IMService imService;

    /**
     * 展示个人数据
     *
     * @param userId
     * @return
     */
    public TodayBest queryUserInfo(Long userId) {
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        if (ObjectUtil.isEmpty(userId)) {
            return null;
        }
        TodayBest todayBest = new TodayBest();
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ",")));
        todayBest.setAvatar(userInfo.getLogo());
        //缘分值
        User user = UserThreadLocal.get();
        todayBest.setFateValue(this.recommendUserService.queryScore(userId, user.getId()).longValue());
        //记录来访用户
        this.visitorsApi.saveVisitor(userId, user.getId(), "个人主页");
        return todayBest;
    }

    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (ObjectUtil.isEmpty(question)) {
            //没有问题 默认使用数据库的
            return "你的一生的追求是什么?";
        }
        return question.getTxt();
    }

    /**
     * 回复陌生人问题
     *
     * @return userid是对方id
     */
    public boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        //查询当前用户的信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(user.getId());
        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId());
        msg.put("hanxinId", "HX_" + user.getId());
        msg.put("nieckname", userInfo.getNickName());
        msg.put("strangerQuestion", this.queryQuestion(userId));
        msg.put("reply", reply);
        //发送信息
        return this.huanXinApi.sendMsgFromAdmin("HX_" + userId, HuanXinMessageType.TXT, JSONUtil.toJsonPrettyStr(msg));
    }

    /**
     * 搜附近
     *
     * @param gender   性别
     * @param distance 距离m
     * @return
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //查询当前用户
        User user = UserThreadLocal.get();
        //先去查询当前用户的地址
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        if (ObjectUtil.isEmpty(userLocationVo)) {
            //没有查询到地址
            return ListUtil.empty();//返回一个空的集合
        }
        //查询到位置后就调用范围查询方法  根据用户当前的位置 可以查出当前经度纬度
        PageInfo<UserLocationVo> pageInfo = this.userLocationApi.queryUserFromLocation(userLocationVo.getLongitude(),
                userLocationVo.getLatitude(),
                Convert.toDouble(distance), //搜索距离M
                1,
                50
        );
        //获取里面的数据列表
        List<UserLocationVo> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            //没有查到附近其他用户
            return ListUtil.empty();
        }
//查到有用户 但是不知道性别 所以要筛选
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("userId", userIdList);
        if (StrUtil.equalsIgnoreCase(gender, "man")) { //判断小写  是否是man
            queryWrapper.eq("sex", SexEnum.MAN);  //是man 查询条件man
        } else {
            queryWrapper.eq("sex", SexEnum.WOMAN);//s是woman 查询条件woman
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<NearUserVo> result = new ArrayList<>();//用来装满足条件的用户
        for (UserLocationVo locationVo : records) {
            if (ObjectUtil.equals(locationVo.getUserId(), user.getId())) {
                //当附近收到的用户id 和自己相等 那就是收到自己 不用添加到分页列表里面
                continue;
            }
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(locationVo.getUserId(), userInfo.getUserId())) {
                    NearUserVo nearUserVo = new NearUserVo();
                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());
                    result.add(nearUserVo);
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 探花
     *
     * @return
     */
    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        int count = 50;
        //查询到的50条数据，并不是用来直接展现，需要从这50条数据中随机返回一些数据
        List<RecommendUser> recommendUserList = this.recommendUserService.queryCardList(user.getId(), count);
        if (CollUtil.isEmpty(recommendUserList)) {
            recommendUserList = new ArrayList<>();
            //没有推荐数据 就默认推荐
            List<String> list = StrUtil.split(defaultRecommendUsers, ',');

            for (String userId : list) {
                //推荐用户的Id
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setToUserId(user.getId());
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUserList.add(recommendUser);
            }
        }
        //有数据时  默认展示10个  没有10个就展示所以
        int showCount = Math.min(10, recommendUserList.size());
        List<RecommendUser> result = new ArrayList<>();
        for (int i = 0; i < showCount; i++) {
            //随机展示
            int index = RandomUtil.randomInt(0, recommendUserList.size());
            RecommendUser recommendUser = recommendUserList.get(index);
            result.add(recommendUser);
        }
        List<Object> userIdList = CollUtil.getFieldValues(result, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIdList);
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));
            todayBest.setFateValue(0L);
            todayBests.add(todayBest);
        }
        return todayBests;
    }

    /**
     * 不喜欢
     *
     * @param likeUserId
     * @return
     */
    public Boolean notLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.notLikeUser(user.getId(), likeUserId);
    }

    /**
     * 喜欢
     *
     * @param likeUserId
     * @return
     */
    public Boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        Boolean bool = this.userLikeApi.likeUser(user.getId(), likeUserId);
        if (!bool) {
            return false;
        }
        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }
        return true;
    }
}
